package org.wei.db.mongo;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

public class MongoDbHelperFactory {
	private static MongoDbHelper mongoDbHelper;

	private MongoDbHelperFactory() {
	}

	private static MongoDbHelper createUtil(String dbName) {
		List<ServerAddress> servers = new ArrayList<ServerAddress>();
		for (NetAddress netAddress : MongoDbSetting.getInstance().getServers()) {
			servers.add(new ServerAddress(new InetSocketAddress(netAddress
					.getHost(), netAddress.getPort())));
		}
		List<MongoCredential> credentials = new ArrayList<MongoCredential>();
		for (DbCredential credential : MongoDbSetting.getInstance()
				.getCredentials()) {
			credentials.add(MongoCredential.createCredential(
					credential.getUsername(), credential.getDbName(),
					credential.getPassword().toCharArray()));
		}
		MongoClient mongoClient = new MongoClient(servers, credentials);
		mongoClient.setWriteConcern(MongoDbSetting.DEFALTE_WRITE_CONCERN);
		MongoDbHelper mongoDbHelper = new MongoDbHelper(mongoClient, dbName);
		return mongoDbHelper;
	}

	private static MongoDbHelper createDefaultUtil() {
		return createUtil(MongoDbSetting.getInstance().getDbName());
	}

	public synchronized static MongoDbHelper getMongoDbHelper() {
		if (mongoDbHelper == null) {
			mongoDbHelper = createDefaultUtil();
		}
		return mongoDbHelper;
	}

}
